package ar.edu.itba.twiteros.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.http.AccessToken;
import ar.edu.itba.twiteros.dao.UserDao;
import ar.edu.itba.twiteros.domain.UserIds;
import ar.edu.itba.twiteros.util.Facebook;
import ar.edu.itba.twiteros.util.GrantTwitterAccess;

import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookParam;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet{

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
	}
	/*
	 <td><img src='<c:out value="${status.getUser.getProfileImageURL}" escapeXml="true" />'/></td>
	 */
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		RequestDispatcher dispacher= getServletContext().getRequestDispatcher("/index");
		
		Facebook facebook= new Facebook(req.getParameter(FacebookParam.SESSION_KEY.toString()));
		Long uid=null;
		
		try {
			uid = facebook.getClient().users_getLoggedInUser();
		} catch (FacebookException e) {
			req.setAttribute("error_message", e.getMessage());
			dispacher= getServletContext().getRequestDispatcher("/error.jsp");
			dispacher.forward(req, resp);
		}
		
		Twitter twitter= new Twitter();
		UserIds user= UserDao.getUser(uid);
		
		twitter.setOAuthConsumer(GrantTwitterAccess.getConsumerKey(), 
				GrantTwitterAccess.getConsumerSecret());
		
		if(user!=null){
			AccessToken accessToken;
			try {
				accessToken = twitter.getOAuthAccessToken(user.getToken(), user.getTokenSecret());
				twitter.setOAuthAccessToken(accessToken);
				
				user.setToken(accessToken.getToken());
				user.setTokenSecret(accessToken.getTokenSecret());
				user.setAccess(true);
				
				UserDao.save(user);
				
			} catch (TwitterException e) {
				req.setAttribute("error_message", e.getMessage());
				dispacher= getServletContext().getRequestDispatcher("/error.jsp");
				dispacher.forward(req, resp);
			}
		}
		
		dispacher.forward(req, resp);
		
	}

	
}
